package com.example.exam.user.service;

import com.example.exam.user.dao.UserRoleDao;
import com.example.exam.user.model.UserRoleBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class UserRoleService {
	
	@Autowired
	private UserRoleDao userRoleDao;
	@Transactional
	/**
	 * @Description:
	 * @Param: [roleIds, userId, request]
	 * @return: java.lang.Integer
	 * @Author: xhw
	 * @Date: 2021/7/26
	 */
	public Integer save(Integer[] roleIds, Integer userId, HttpServletRequest request) {

		Integer rows  = 0;
		try {
			if(roleIds==null) {
				userRoleDao.deleteByUserId(userId);
				return 1;
			}
			userRoleDao.deleteByUserId(userId);
			HttpSession session=request.getSession();
			Integer createUser=(Integer) session.getAttribute("id");
			int length = roleIds.length;
			for (int i = 0; i < length; i++) {
				UserRoleBean userRoleBean = new UserRoleBean();
				userRoleBean.setUserId(userId);
				userRoleBean.setRoleId(roleIds[i]);
				userRoleBean.setState(1);
				userRoleBean.setCreateUser(createUser);
				userRoleBean.setCreateTime(new Date());
				rows=userRoleDao.add(userRoleBean);
			}
		} catch (Exception e) {
			e.fillInStackTrace();
			return 0;
		}
		return rows;
	}/**
	 * @Description:
	 * @Param: [id]
	 * @return: java.util.List
	 * @Author: xhw
	 * @Date: 2021/7/26
	 */
	public List authorization(Integer id){

		List list=userRoleDao.authorization(id);
		if (list.size()>0){
			return list;
		}else{
			return null;
		}
	}
}
